package cn.westv.scps.web.controller.bikeowner;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import cn.westv.scps.utils.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.westv.scps.connTools.ProxyConnExec;
import cn.westv.scps.constant.ConfigCodeConstant;
import cn.westv.scps.constant.SmsTplCodeConstant;
import cn.westv.scps.domain.AreaSeverEntity;
import cn.westv.scps.domain.BikeOwnerEntity;
import cn.westv.scps.exception.NoHaveValidateCode;
import cn.westv.scps.exception.ValiDateCodeTimeout;
import cn.westv.scps.exception.ValidateCodeErr;
import cn.westv.scps.service.areaserver.IAreaServerService;
import cn.westv.scps.service.bikeowner.IBikeOwnerService;
import cn.westv.scps.service.sys.config.ISysConfigService;
import cn.westv.scps.web.controller.base.AbstractController;
import cn.westv.scps.web.utils.SendSmsTools;

/**
 * 
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/bike/owner")
public class BikeOwnerController extends AbstractController<BikeOwnerController> {
	@Resource
	private IAreaServerService areaServerService;
	@Resource
	private IBikeOwnerService bikeOwnerService;
	@Resource
	private ISysConfigService sysConfigService;

	/**
	 * 获取用户电话号码
	 * 
	 * @param serverId
	 * @return
	 */
	@RequestMapping("/mobile")
	@ResponseBody
	public Map<String, Object> getMobile(String serverId) {
		try {
			Collection<BikeOwnerEntity> ownerColl = null;
			ArrayList<Object> params = new ArrayList<>();
			ArrayList<String> mobileList = new ArrayList<>();
			String hql = "from BikeOwnerEntity where 1 = 1 ";
			if (StringUtils.isNotBlank(serverId)) {
				hql += "and areaSever.serverId = ?";
				params.add(serverId);
			}
			ownerColl = bikeOwnerService.find(hql, BikeOwnerEntity.class, params.toArray());
			for (BikeOwnerEntity owner : ownerColl) {
				mobileList.add(owner.getMobile());
			}
			return ajaxReturnMap(OP_STATUS_SUCCESS, "", mobileList);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 根据账号获取用户所属的服务器<br>
	 * 用户登录以前，可能数据库中不存在用户的资料，需要想base服务器请求用户资料<br>
	 * 
	 * @param account
	 * @return
	 */
	@RequestMapping("/mapper")
	@ResponseBody
	public Map<String, Object> mapper(String account) {
		try {
			if (StringUtils.isEmpty(account)) {
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.LOGIN_FAILURE), null);// 用户名为空，返回错误信息
			}
			JSONObject json = null;
			BikeOwnerEntity entity = null;
			List<BikeOwnerEntity> find = bikeOwnerService.find("from BikeOwnerEntity where account = ? or mobile = ?",
					BikeOwnerEntity.class, new Object[] { account, account });// 根据账号查询用户
			AreaSeverEntity areaSever = null;
			if (find != null && find.size() > 0) {// 在数据库中可以找到该用户
				entity = find.get(0);
				areaSever = entity.getAreaSever();// 获取用户所匹配的服务器
			} else {
				// 无法找到该用户时，向base服务器请求用户信息
//				JSONObject rsJson = ProxyConnExec.getOwnerDatum(account);
//				if (rsJson != null) {// 找到了用户
//					areaSever = areaServerService.findByAreaCode(rsJson.getJSONObject("data").getString("areaCode"));
//				}
			}
			if (areaSever != null) {
				json = new JSONObject();
				// json.put("account", entity.getAccount());
				json.put("serverName", areaSever.getServerName());
				json.put("contextPath", areaSever.getContextPath());
				json.put("areaCode", areaSever.getAreaCode());
				json.put("mqttHostIp", areaSever.getMqttHostIp());
				json.put("socketPort", areaSever.getMqttSocketHostPort());
				json.put("tcpPort", areaSever.getMqttTcpHostPort());
				json.put("serverId", areaSever.getServerId());
				return ajaxReturnMap(OP_STATUS_SUCCESS, "", json);// 匹配成功，返回匹配的服务器信息
			} else {// 没有找到用户
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_OWNER), null);// 用户名不存在
			}
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 发送注册请求以前，需要访问此url进行用户资料的初始化
	 * 
	 * @param invitationCode
	 *            邀请码，前六位是地区编码
	 * @return
	 */
//	@RequestMapping("/init/ownerinfo")
	@ResponseBody
	@Deprecated
	public Map<String, Object> initOwnerInfo(String invitationCode) {
		try {
			String areaCode = invitationCode.substring(0, 6);// 解析邀请码前六位
			List<AreaSeverEntity> find = areaServerService.find("from AreaSeverEntity where areaCode like ?",
					AreaSeverEntity.class, new Object[] { "%" + areaCode + "%" });// 根据邀请码前六位，模糊查询服务器

			if (find == null || find.size() < 1) {// 查询不到服务器
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.SN_CODE_ERR), null);
			}
			AreaSeverEntity areaSeverEntity = find.get(0);
			JSONObject json = ProxyConnExec.getOwnerInfoByApplayCode(invitationCode, areaSeverEntity);
			if (json != null) {
				String opStatus = json.getString("opStatus");
				if (OP_STATUS_SUCCESS.equals(opStatus)) {
					JSONObject data = json.getJSONObject("data");
					String mobile = data.getString("mobile");
					String account = data.getString("account");
					BikeOwnerEntity entity = new BikeOwnerEntity();
					entity.setAccount(account);
					entity.setMobile(mobile);
					entity.setAreaSever(areaSeverEntity);
					bikeOwnerService.saveOrUpdate(entity);
					return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.INIT_OWNERINFO_SUCCEED), null);
				} else {
					return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
				}
			}
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 用户注册
	 * 
	 * @param invitationCode
	 *            邀请码，前六位是地区编码
	 * @param mobile
	 *            手机
	 * @param validateCode
	 *            手机验证码
	 * @param password
	 *            密码
	 * @return
	 */
	@RequestMapping("/register")
	@ResponseBody
	public Map<String, Object> ownerRegister(String invitationCode, String mobile, String validateCode,
			String password) {
		try {
			if (StringUtils.isEmpty(invitationCode) || StringUtils.isEmpty(mobile) || StringUtils.isEmpty(validateCode)
					|| StringUtils.isEmpty(password)) {// 判读必选参数是否为空
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.REQUIRED_PARAMETERS_IS_NULL), null);
			}
			// ----------------------先判断用户的手机号是否通过验证-----------------------------
			SendSmsTools sst = new SendSmsTools();
			try {
				sst.checkMobileValidateCode(mobile, validateCode, SmsTplCodeConstant.OWNER_REGISTER, 1800000L);
			} catch (ValidateCodeErr e1) {// 验证码错误
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg("validate_code_err"), null);// 返回验证码错误提示
			} catch (ValiDateCodeTimeout e2) {// 验证码超时
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg("validate_code_timeout"), null);// 返回验证码超时提示
			} catch (NoHaveValidateCode e3) {// 没有对应的手机验证码（可能是短信发送后超过1天，也可能是没有发送过短信，也可能是之前成注册过了）
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg("validate_code_timeout"), null);// 验证码超过1天，或者没有发送过手机验证短信，返回验证码超时
			}
			// ----------------------先判断用户的手机号是否通过验证-----------------------------

			String areaCode = invitationCode.substring(0, 6);// 解析邀请码前六位
			List<AreaSeverEntity> find = areaServerService.find("from AreaSeverEntity where areaCode like ?",
					AreaSeverEntity.class, new Object[] { "%" + areaCode + "%" });// 根据邀请码前六位，模糊查询服务器
			if (find == null || find.size() < 1) {// 查询不到服务器
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.SN_CODE_ERR), null);
			}
			JSONObject jsonObject = ProxyConnExec.ownerRegistSubmit(invitationCode, mobile, password, find.get(0));// 将注册表单发送给对应服务器，进行用户注册
			if (jsonObject != null) {
				if (OP_STATUS_SUCCESS.equals(jsonObject.getString("opStatus"))) {// 注册成功后
					BikeOwnerEntity bikeOwner = new BikeOwnerEntity();
					bikeOwner.setAccount(mobile);// 手机号码即是账号
					bikeOwner.setMobile(mobile);
					bikeOwner.setAreaSever(find.get(0));
					bikeOwnerService.saveOrUpdate(bikeOwner);// 将用户信息保存到代理服务器的数据库
					SendSmsTools.mobileValidateMap.remove(mobile);// 删除短信验证码的对应关系，即之前注册用的短信验证码失效
				}
				return ajaxReturnMap(jsonObject.getString("opStatus"), jsonObject.getString("msgDesc"),
						jsonObject.get("data"));
			}
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 用户修改手机号码
	 * 
	 * @param newValidateCode
	 *            短信验证码
	 * @param newMobile
	 *            新手机
	 * @param oldMobile
	 *            旧手机
	 * @return
	 */
	@RequestMapping("/change/mobile")
	@ResponseBody
	public Map<String, Object> changeMobile(String newValidateCode, String oldValidateCode, String newMobile,
			String oldMobile, String password, String serverId, String token,String isWechat) {
		try {
			if (StringUtils.isEmpty(oldValidateCode) || StringUtils.isEmpty(newValidateCode)
					|| StringUtils.isEmpty(password) || StringUtils.isEmpty(newMobile) || StringUtils.isEmpty(oldMobile)
					|| StringUtils.isEmpty(serverId) || StringUtils.isEmpty(token)) {// 判读必选参数是否为空
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.REQUIRED_PARAMETERS_IS_NULL), null);
			}
			// 查找数据库中是否已经存在了新手机号码的用户，如果存在，则不允许修改
			BikeOwnerEntity newMobileOwner = bikeOwnerService.findByMobile(newMobile);
			if(newMobileOwner != null){
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.EXISTED_MOBILE), null);
			}
			// ----------------------判断用户的手机号是否通过验证-----------------------------
			SendSmsTools sst = new SendSmsTools();
			try {
				sst.checkMobileValidateCode(oldMobile, oldValidateCode, SmsTplCodeConstant.OLD_OWNER_CHANGE_MOBILE_GPS,
						300000L);// 5分钟内验证码有效
			} catch (ValidateCodeErr e1) {// 验证码错误
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.VALIDATE_CODE_ERR), oldMobile);// 返回验证码错误提示
			} catch (ValiDateCodeTimeout e2) {// 验证码超时
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.VALIDATE_CODE_TIMEOUT), oldMobile);// 返回验证码超时提示
			} catch (NoHaveValidateCode e3) {// 没有对应的手机验证码（可能是短信发送后超过1天，也可能是没有发送过短信，也可能是之前成注册过了）
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.VALIDATE_CODE_ERR), oldMobile);// 验证码超过1天，或者没有发送过手机验证短信，返回验证码超时,或者是用户手机号码输入错误
			}
			try {
				sst.checkMobileValidateCode(newMobile, newValidateCode, SmsTplCodeConstant.OWNER_CHANGE_MOBILE_GPS,
						300000L);// 5分钟内验证码有效
			} catch (ValidateCodeErr e1) {// 验证码错误
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.VALIDATE_CODE_ERR), newMobile);// 返回验证码错误提示
			} catch (ValiDateCodeTimeout e2) {// 验证码超时
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.VALIDATE_CODE_TIMEOUT), newMobile);// 返回验证码超时提示
			} catch (NoHaveValidateCode e3) {// 没有对应的手机验证码（可能是短信发送后超过1天，也可能是没有发送过短信，也可能是之前成注册过了）
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.VALIDATE_CODE_ERR), newMobile);// 验证码超过1天，或者没有发送过手机验证短信，返回验证码超时,或者是用户手机号码输入错误
			}

			// ----------------------判断用户的手机号是否通过验证-----------------------------
			AreaSeverEntity areaSever = areaServerService.get(AreaSeverEntity.class, serverId);
			if (areaSever == null) {// 无法匹配到服务器
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.NOTFIND_OWNER_MAPPER_SERVER), null);
			}

			// -------------------判断该手机号码是否是对应当前已经登录的用户-----------------（这个判断交给base服务器进行判断）
			// JSONObject json = ProxyConnExec.mobileVerify(token, oldMobile,
			// areaSever);// 向对用的服务器后台请求验证
			// if (json != null) {
			// String opStatus = json.getString("opStatus");
			// if (opStatus.equals(OP_STATUS_SUCCESS)) {// 正确请求并返回参数
			// if (json.getBoolean("data") == false) {//
			// 返回的值false，说明token和mobile不匹配，不允许修改手机号码
			// return ajaxReturnMap(OP_STATUS_FAILD,
			// returnMsg("mobile_mismatching_token"), null);// 不匹配，返回错误，不进行手机修改
			// }
			// } else {
			// return ajaxReturnMap(opStatus, json.getString("msgDesc"),
			// json.get("data"));// 请求失败，或者错误请求
			// }
			// } else {
			// return ajaxReturnMap(OP_STATUS_FAILD, returnMsg("unknown_err"),
			// null);// 未知的错误
			// }
			// -------------------判断该手机号码是否是对应当前已经登录的用户-----------------

			BikeOwnerEntity entity = bikeOwnerService.findByMobile(oldMobile);// 验证通过，开始执行修改数据库的代码
			if (entity != null) {
				// 发送修改手机号码的请求
				JSONObject jsonObject = ProxyConnExec.changeMobile(isWechat,token, oldMobile, newMobile, password, "app",
						areaSever);
				if (jsonObject != null && OP_STATUS_SUCCESS.equals(jsonObject.getString("opStatus"))) {// base服务器修改成了，再修改代理服务器的手机号码
					entity.setMobile(newMobile);// 修改手机号
					entity.setAccount(newMobile);
					bikeOwnerService.saveOrUpdate(entity);
				}
				return ajaxReturnMap(jsonObject.getString("opStatus"), jsonObject.getString("msgDesc"),
						jsonObject.get("data"));
			} else {
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.MOBILE_UNBOUND), null);
			}
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 用户忘记密码后，提交重置密码的请求
	 */
	@RequestMapping("/forget/pwd")
	@ResponseBody
	public Map<String, Object> forgetPwd(String mobile, String validateCode, String password, String serverId,
			String isWechat) {
		try {
			if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(validateCode) || StringUtils.isEmpty(password)
					|| StringUtils.isEmpty(serverId)) {// 判读必选参数是否为空
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.REQUIRED_PARAMETERS_IS_NULL), null);
			}
			// ----------------------先判断用户的手机号是否通过验证-----------------------------
			SendSmsTools sst = new SendSmsTools();
			try {
				sst.checkMobileValidateCode(mobile, validateCode, SmsTplCodeConstant.OWNER_RETRIEVE_PASSWORD_GPS,
						900000L);// 15分钟内验证码有效
			} catch (ValidateCodeErr e1) {// 验证码错误
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.VALIDATE_CODE_ERR), null);// 返回验证码错误提示
			} catch (ValiDateCodeTimeout e2) {// 验证码超时
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.VALIDATE_CODE_TIMEOUT), null);// 返回验证码超时提示
			} catch (NoHaveValidateCode e3) {// 没有对应的手机验证码（可能是短信发送后超过1天，也可能是没有发送过短信，也可能是之前成注册过了）
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.VALIDATE_CODE_TIMEOUT), null);// 验证码超过1天，或者没有发送过手机验证短信，返回验证码超时,或者是用户手机号码输入错误
			}
			// ----------------------先判断用户的手机号是否通过验证-----------------------------

			AreaSeverEntity areaSeverEntity = areaServerService.get(AreaSeverEntity.class, serverId);
			if (areaSeverEntity != null) {
				JSONObject json = ProxyConnExec.forgetPassword(mobile, password, isWechat, areaSeverEntity);
				return ajaxReturnMap(json.getString("opStatus"), json.getString("msgDesc"), json.get("data"));
			} else {
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.NOTFIND_OWNER_MAPPER_SERVER), null);
			}
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 游客登录，验证手机号码是否正确
	 * 
	 * @param mobile
	 * @param validateCode
	 * @return
	 */
	@RequestMapping("/visitor/login")
	@ResponseBody
	public Map<String, Object> visitorLogin(String mobile, String validateCode) {
		try {
			SendSmsTools sst = new SendSmsTools();
			try {
				sst.checkMobileValidateCode(mobile, validateCode, SmsTplCodeConstant.VISITOR_LOGIN, 900000L);// 15分钟内验证码有效
			} catch (ValidateCodeErr e1) {// 验证码错误
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.VALIDATE_CODE_ERR), null);// 返回验证码错误提示
			} catch (ValiDateCodeTimeout e2) {// 验证码超时
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.VALIDATE_CODE_TIMEOUT), null);// 返回验证码超时提示
			} catch (NoHaveValidateCode e3) {// 没有对应的手机验证码（可能是短信发送后超过1天，也可能是没有发送过短信，也可能是之前成注册过了）
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.VALIDATE_CODE_TIMEOUT), null);// 验证码超过1天，或者没有发送过手机验证短信，返回验证码超时,或者是用户手机号码输入错误
			}
			return ajaxReturnMap(OP_STATUS_SUCCESS, "", null);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 车主解除车辆绑定
	 * 
	 * @param token
	 * @param regiId
	 * @param mobile
	 * @param validateCode
	 * @return
	 */
	@RequestMapping("/registation/unbind")
	@ResponseBody
	public Map<String, Object> registatioNunbind(String token, String regiId, String mobile, String validateCode) {
		if (StringUtils.isEmpty(token) || StringUtils.isEmpty(validateCode) || StringUtils.isEmpty(regiId)
				|| StringUtils.isEmpty(mobile)) {// 判读必选参数是否为空
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.REQUIRED_PARAMETERS_IS_NULL), null);
		}
		try {
			// ----------------------先判断用户的手机号是否通过验证-----------------------------
			SendSmsTools sst = new SendSmsTools();
			try {
				// 测试临时扩大短信超时时间
				sst.checkMobileValidateCode(mobile, validateCode, SmsTplCodeConstant.DEL_BIKE, 3000000L);// 5分钟内验证码有效
			} catch (ValidateCodeErr e1) {// 验证码错误
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.VALIDATE_CODE_ERR), null);// 返回验证码错误提示
			} catch (ValiDateCodeTimeout e2) {// 验证码超时
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.VALIDATE_CODE_TIMEOUT), null);// 返回验证码超时提示
			} catch (NoHaveValidateCode e3) {// 没有对应的手机验证码（可能是短信发送后超过1天，也可能是没有发送过短信，也可能是之前成注册过了）
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.VALIDATE_CODE_TIMEOUT), null);// 验证码超过1天，或者没有发送过手机验证短信，返回验证码超时,或者是用户手机号码输入错误
			}
			// ----------------------先判断用户的手机号是否通过验证-----------------------------
			BikeOwnerEntity owner = bikeOwnerService.findByMobile(mobile);
			if (owner != null && owner.getAreaSever() != null) {
				JSONObject jsonObject = ProxyConnExec.registatioNunbind(token, regiId, owner.getAreaSever());
				if (jsonObject != null) {
					return ajaxReturnMap(jsonObject.getString("opStatus"), jsonObject.getString("msgDesc"),
							jsonObject.get("data"));
				} else {
					return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
				}
			} else {
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.NOTFIND_OWNER_MAPPER_SERVER), null);
			}
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}

	}

	/**
	 * 根据SN码获取对应的公钥
	 * 
	 * @param invitationCode
	 * @return
	 */
	@RequestMapping("/publickey")
	@ResponseBody
	public Map<String, Object> getPublicKey(String invitationCode) {
		if (StringUtils.isEmpty(invitationCode)) {// 判读必选参数是否为空
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.REQUIRED_PARAMETERS_IS_NULL), null);
		}
		try {
			if(invitationCode.length() != 16 ){
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.SN_CODE_ERR), null);
			}
			String areaCode = invitationCode.substring(0, 6);// 解析邀请码前六位
			List<AreaSeverEntity> find = areaServerService.find("from AreaSeverEntity where areaCode like ?",
					AreaSeverEntity.class, new Object[] { "%" + areaCode + "%" });// 根据邀请码前六位，模糊查询服务器
			if (find == null || find.size() < 1) {// 查询不到服务器
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.SN_CODE_ERR), null);
			}
			AreaSeverEntity areaSeverEntity = find.get(0);
			Map<String, String> map = ProxyConnExec.getPublicKeyBySNcode(areaSeverEntity);
			return ajaxReturnMap(OP_STATUS_SUCCESS, "", map);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 微信绑定用户
	 * 
	 * @param ownerId
	 * @param openid
	 * @param serverId
	 * @return
	 */
	@RequestMapping("/wechatbind")
	@ResponseBody
	public Map<String, Object> wechatbind(String ownerId, String openid, String serverId) {
		try {
			AreaSeverEntity server = areaServerService.get(AreaSeverEntity.class, serverId);
			JSONObject res = ProxyConnExec.wechatbind(ownerId, openid, server);
			return ajaxReturnMap(res.getString("opStatus"), res.getString("msgDesc"), res.get("data"));
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 微信解绑用户
	 * 
	 * @param ownerId
	 * @param serverId
	 * @return
	 */
	@RequestMapping("/wechatunbind")
	@ResponseBody
	public Map<String, Object> wechatunbind(String ownerId, String serverId) {
		try {
			AreaSeverEntity server = areaServerService.get(AreaSeverEntity.class, serverId);
			JSONObject res = ProxyConnExec.wechatunbind(ownerId, server);
			return ajaxReturnMap(res.getString("opStatus"), res.getString("msgDesc"), res.get("data"));
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 发卡APP 添加用户注册
	 */
	@RequestMapping("/regist")
	@ResponseBody
	public  Map<String,Object> initRegist(String mobile ,String invitationCode){
		String areaCode = invitationCode.substring(0, 6);// 解析邀请码前六位
		List<AreaSeverEntity> find = areaServerService.find("from AreaSeverEntity where areaCode like ?",
				AreaSeverEntity.class, new Object[] { "%" + areaCode + "%" });// 根据邀请码前六位，模糊查询服务器
		if (find == null || find.size() < 1) {// 查询不到服务器
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.SN_CODE_ERR), null);

		}else{
			BikeOwnerEntity entity = bikeOwnerService.findByMobile(mobile);
			if(entity != null){
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.EXISTED_MOBILE), null);
			}else{
				entity = new BikeOwnerEntity();
				entity.setMobile(mobile);
				entity.setAccount(mobile);
				entity.setAreaSever(find.get(0));
				bikeOwnerService.saveOrUpdate(entity);
			}
		}
		return ajaxReturnMap(OP_STATUS_SUCCESS,returnMsg(ConfigCodeConstant.ADD_SUCCEED),null);

	}

}
